const { Transform } = require('stream');
const _ = require('lodash');
const moment = require('moment');
const utils = require('../../utils');

module.exports = function (type, inFormat) {
  const stream = new Transform({ objectMode: true });
  if (_.isFunction(type)) {
    inFormat = type;
    type = undefined;
  }
  inFormat = utils.parseFunction(inFormat);
  stream._transform = async function (chunk, encoding, callback) {
    utils.debug('formatTransform [chunk]:', chunk);
    let line = chunk;
    if (type !== undefined) {
      line = utils.stringify(chunk, type);
    }
    line = inFormat ? await inFormat(line, { _, moment, utils }) : line;
    stream.push(line);
    callback();
  };
  stream.on('finish', function () {
    utils.debug('formatTransform [finish]');
  });
  return stream;
};